import time
import yaml
from selenium import webdriver


class BasePage:
    _base_url = None

    def __init__(self, base_driver=None):
        if base_driver:
            self.driver = base_driver
        else:
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.implicitly_wait(10)

            if self._base_url:
                self.driver.get(self._base_url)

                # # 等待扫码登录完成，并获取cookies,写入yaml文件
                # time.sleep(40)
                # cookies = self.driver.get_cookies()
                # with open("../datas/cookies.yaml", "w") as f:
                #     yaml.safe_dump(cookies, f)

                # 从yaml文件中读取 cookie 文件
                with open("../datas/cookies.yaml", "r") as f:
                    cookies = yaml.safe_load(f)
                # 向浏览器添加cookie
                for cookie in cookies:
                    self.driver.add_cookie(cookie)
                self.driver.get(self._base_url)
            else:
                self.driver.quit()

    def find(self, by, selector=None):
        if selector:
            ele = self.driver.find_element(by, selector)
        else:
            ele = self.driver.find_element(*by)

        return ele

    def finds(self, by, selector=None):
        if selector:
            ele_list = self.driver.find_elements(by, selector)
        else:
            ele_list = self.driver.find_elements(*by)

        return ele_list
